<template>
  <!-- 账号设置 -->
  <div class="account-settings" :style="{ paddingTop: capsuleTop + 'px' }">
    <Return />

    <div class="settings-content">
      <!-- 头像设置 -->
      <div class="settings-item">
        <div class="settings-item-title">头像</div>
        <div class="settings-item-content">
          <div class="avatar-upload" @click="chooseAvatar">
            <img :src="formData.headImgUrl?formData.headImgUrl:'../static/imgs/touxiang.png'" class="avatar-image">
            <div class="upload-icon">
              <wd-icon name="camera" size="24rpx"></wd-icon>
            </div>
          </div>
        </div>
      </div>

      <!-- 用户名称 -->
      <div class="settings-item">
        <div class="settings-item-title">用户名称</div>
        <div class="settings-item-content">
          <input class="settings-input" type="text" placeholder="请输入用户名称" v-model="formData.customerName"
            maxlength="20" />
        </div>
      </div>

      <!-- 性别选择 -->
      <!-- <div class="settings-item">
        <div class="settings-item-title">性别</div>
        <div class="settings-item-content">
          <picker class="settings-picker" :range="genderOptions" range-key="label" :value="genderIndex"
            @change="handleGenderChange">
            <div class="picker-text">
              {{ getGenderLabel(formData.six) || '请选择性别' }}
            </div>
          </picker>
        </div>
      </div> -->

      <!-- 手机号码 -->
      <div class="settings-item">
        <div class="settings-item-title">手机号码</div>
        <div class="settings-item-content">
          <input class="settings-input" type="number" placeholder="请输入手机号码" v-model="formData.phone" maxlength="11" />
        </div>
      </div>
    </div>

    <!-- 保存按钮 -->
    <div class="footer">
      <div
        class="feedback-box-class-submit"
        :class="{ disabled: saving }"
        @click="debouncedSaveSettings"
      >
        {{ saving ? '提交中...' : '提交' }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
// 获取用户数据
import { useLoginStore } from '@/stores/login'
const loginStore = useLoginStore()
import Return from '@/components/Return.vue'
import { useUserStore } from '@/stores/user'
import { baseUrl } from '@/utils/config'
import { debounce } from '@/utils/debounce'

const userStore = useUserStore()
const capsuleTop = ref(0)
const saving = ref(false)

// 默认头像
const defaultAvatar = '../static/imgs/banner.png'

// 性别选项
const genderOptions = ref([])

// 表单数据
const formData = reactive({
  headImgUrl: userStore.customerInfo?.headImgUrl || '',
  customerName: userStore.customerInfo?.customerName || '',
  six: userStore.customerInfo?.six || '',
  phone: userStore.customerInfo?.phone || ''
})

// 计算头像URL
const avatarUrl = computed(() => {
  if (formData.avatarFileId) {
    return `${baseUrl}shopping/sysFile/${formData.avatarFileId}`
  }
  return formData.avatar || defaultAvatar
})

// 获取性别索引
const genderIndex = computed(() => {
  return genderOptions.value.findIndex(item => item.value == formData.six||1)
})

// 获取性别标签
const getGenderLabel = (value) => {
  const option = genderOptions.value.find(item => item.value == value)
  return option ? option.label : ''
}

// 处理性别选择
const handleGenderChange = (e) => {
  const index = e.detail.value
  formData.six = genderOptions.value[index].value
}

// 选择头像
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['camera', 'album'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0]
      uploadAvatar(tempFilePath)
    },
    fail: (err) => {
      console.log('选择图片失败:', err)
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  })
}

// 上传头像
const uploadAvatar = async (filePath) => {
  uni.showLoading({
    title: '上传中...'
  })

  try {
    // 使用uni.uploadFile上传文件
    uni.uploadFile({
      url: `${baseUrl}shopping/sysFile/upload`, // 文件上传接口
      filePath: filePath,
      name: 'file',
      header: {
        'accesstoken': loginStore.token || ''
      },
      success: (uploadResult) => {
        try {
          const data = JSON.parse(uploadResult.data)
          console.log('上传结果:', data)

          if (data.code === 200) {
            // 假设返回的数据结构包含fileId
            const avatarUrl = data.data?.fileUrl
            if (avatarUrl) {
              formData.headImgUrl = avatarUrl

              uni.showToast({
                title: '头像上传成功',
                icon: 'success'
              })
            }
          } else {
            uni.showToast({
              title: data.msg || '头像上传失败',
              icon: 'none'
            })
          }
        } catch (parseError) {
          console.error('解析上传结果失败:', parseError)
          uni.showToast({
            title: '头像上传失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.log('上传失败:', err)
        uni.showToast({
          title: '头像上传失败',
          icon: 'none'
        })
      },
      complete: () => {
        uni.hideLoading()
      }
    })
  } catch (error) {
    console.error('上传头像错误:', error)
    uni.hideLoading()
    uni.showToast({
      title: '头像上传失败',
      icon: 'none'
    })
  }
}

// 表单验证
const validateForm = () => {
  if (!formData.customerName.trim()) {
    uni.showToast({
      title: '请输入用户名称',
      icon: 'none'
    })
    return false
  }

  if (formData.phone && !/^1[3-9]\d{9}$/.test(formData.phone)) {
    uni.showToast({
      title: '请输入正确的手机号码',
      icon: 'none'
    })
    return false
  }

  return true
}

// 保存设置
const saveSettings = async () => {
  if (!validateForm() || saving.value) return

  saving.value = true

  try {
    const updateData = {
      customerName: formData.customerName,
      six: formData.six,
      phone: formData.phone,
      headImgUrl: formData.headImgUrl,
      customerId: userStore.user.customerId,
    }

    const { status, data } = await Fetch('shopping/customerInfo/edit', {
      method: 'PUT',
      data: updateData
    })

    if (status === 200 && data.code === 200) {
      // 调用方法更新用户数据
      await userStore.getCustomerInfo(userStore.user.customerId)

      uni.showToast({
        title: '保存成功',
        icon: 'success'
      })

      // 延迟返回
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      uni.showToast({
        title: data.msg || '保存失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('保存失败:', error)
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'none'
    })
  } finally {
    saving.value = false
  }
}

// 创建防抖版本的保存方法
const debouncedSaveSettings = debounce(saveSettings, 1000, {
  leading: true,  // 第一次点击立即执行
  trailing: false // 不在延迟结束后执行
})

onMounted(() => {
  const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
  capsuleTop.value = menuButtonInfo.bottom + 20
  getGenderList()
})

// 获取性别数据
const getGenderList = async () => {
  const { data } = await Fetch('shopping/dict/data/type/sys_user_sex', { method: 'get' })
  if (data.code === 200) {

    genderOptions.value = data.data.map(item => ({
      label: item.dictLabel,
      value: item.dictValue,
    }))

  }
}

</script>

<style lang="scss" scoped>
.account-settings {
  min-height: 100vh;
  padding: 0 24rpx;
  background: #F5F5F5;

  .settings-content {
    background: #FFFFFF;
    border-radius: 16rpx;
    margin-top: 20rpx;
    overflow: hidden;

    .settings-item {
      display: flex;
      align-items: center;
      padding: 32rpx 24rpx;
      border-bottom: 1rpx solid #F1F1F2;

      &:last-child {
        border-bottom: none;
      }

      .settings-item-title {
        width: 140rpx;
        font-size: 28rpx;
        color: #191919;
        font-weight: 500;
      }

      .settings-item-content {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        .settings-input {
          flex: 1;
          text-align: right;
          font-size: 28rpx;
          color: #191919;
          border: none;
          outline: none;
          background: transparent;

          &::placeholder {
            color: #CCCCCC;
          }
        }

        .settings-picker {
          flex: 1;
          text-align: right;

          .picker-text {
            font-size: 28rpx;
            color: #191919;
          }
        }

        .avatar-upload {
          position: relative;
          width: 80rpx;
          height: 80rpx;

          .avatar-image {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
          }

          .upload-icon {
            position: absolute;
            bottom: -4rpx;
            right: -4rpx;
            width: 28rpx;
            height: 28rpx;
            background: #007AFF;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 2rpx solid #FFFFFF;

            .wd-icon {
              color: #FFFFFF;
            }
          }
        }
      }
    }

    .footer {
      margin-top: 60rpx;
      padding: 0 24rpx;

      .footer-btn {
        width: 100%;
        height: 88rpx;
        background: #007AFF;
        border-radius: 44rpx;
        border: none;
        color: #FFFFFF;
        font-size: 32rpx;
        font-weight: 500;
        display: flex;
        align-items: center;
        justify-content: center;

        &:disabled {
          background: #CCCCCC;
        }
      }
    }
  }
  .feedback-box-class-submit {
    height: 100rpx;
    background: #FBE050;
    border-radius: 50rpx 50rpx 50rpx 50rpx;
    font-size: 28rpx;
    color: #333333;
    font-weight: bold;
    text-align: center;
    line-height: 100rpx;
    margin-top: 30rpx;
    cursor: pointer;
    transition: all 0.3s ease;

    &.disabled {
      background: #CCCCCC;
      color: #999999;
      cursor: not-allowed;
      pointer-events: none; // 完全禁止点击事件
    }
  }
}
</style>
